#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QFileDialog>
#include <QRegularExpression>

Widget::Widget(ClipboardManager* c, QWidget *parent)
    : QWidget(parent),
      ui(new Ui::Widget),
      cbm(c)
{
    ui->setupUi(this);
    setFixedSize(471,52);
    setWindowTitle("Transfer over clipboard");
}

Widget::~Widget()
{
    delete ui;
}

void Widget::readyToSave(QString name)
{
    ui->label->setText(name);
    ui->pushButton->setEnabled(true);
    ui->pushButton->setText("Save");
    ui->pushButton->disconnect();
    QObject::connect(ui->pushButton, &QPushButton::clicked, [name, this]()
    {
        QString pathToSave = QFileDialog::getSaveFileName(nullptr, QString(), name);
        if (pathToSave.isEmpty()) return;
#ifdef WIN32
        pathToSave.remove(QRegularExpression("^/"));
#endif
        QFile f(pathToSave);
        if (not f.open(QIODevice::WriteOnly))
        {
            ui->label->setText("Failed to write " + pathToSave);
            ui->pushButton->setEnabled(false);
            return;
        }
        f.write(cbm->data());
        f.waitForBytesWritten(10000);
        f.close();
        ui->label->setText(ui->label->text() + " (saved)");
    });
}

void Widget::readyToPrepare(QString name)
{
    ui->label->setText(name);
    ui->pushButton->setEnabled(true);
    ui->pushButton->setText("Prepare!");
    ui->pushButton->disconnect();
    QObject::connect(ui->pushButton, SIGNAL(clicked()), this, SIGNAL(toPrepare()));
}

void Widget::preparedToTransfer(QString name)
{
    ui->label->setText(name);
    ui->pushButton->setEnabled(false);
    ui->pushButton->setText("Ready");
}

void Widget::tooBigSize(QString string)
{
    ui->label->setText(string);
    ui->pushButton->setEnabled(false);
    ui->pushButton->setText("Waiting...");
}

void Widget::clearFields()
{
    ui->label->setText("");
    ui->pushButton->setEnabled(false);
    ui->pushButton->setText("Waiting...");
}

